import React, { forwardRef, useState, useImperativeHandle, ChangeEvent, useRef, useEffect } from 'react';
import { Button, Modal, Input, Table, Space, Form, Pagination, Select, Radio, Upload, DatePicker, Checkbox, DatePickerProps, TreeSelect, Switch, Tooltip } from 'antd';
import { WomanOutlined, ManOutlined, PlusOutlined, InboxOutlined, PaperClipOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import SmartMap from '../../../components/smart-map';
import systemApi from '../../../api/system';
import * as XLSX from "xlsx";
import { addItemToUniquenList, commonErrorMsg, downloadAndRenameFile, getChangeEventValue, getCheckBoxChangeEventValue, getUuid, handleDownloadByName, isEmpty, isNonNegativeNumeric, readWorkBookData, toastShort } from '../../../utils';
import LoadingWapper from '../../../components/loading/LoadingWapper';
import { BJHSpeciesInfoType, SelectOption, SpeciesInfoType, WordParagraphBlock } from '../../../utils/types';
import statisticalAnalysisTools from './../../../statistical-analysis-temp/src';
import { TypeWorkBookReadResult } from '../../../types';
import { CheckboxChangeEvent } from 'antd/lib/checkbox';
import { generateEcologicalBenefit } from '../../office-lib/word-editor-deprecated/WordEditorHelper';
import Image1 from './../../../assets/image/image.svg';
import Image2 from './../../../assets/image/image-2.svg';
import Image3 from './../../../assets/image/image-3.svg';
import Image4 from './../../../assets/image/image-4.svg';
import Image5 from './../../../assets/image/image-5.svg';
import Image6 from './../../../assets/image/image-6.svg';
import { ReportParagraphBlock } from '../../../statistical-analysis-temp/src/typings';

interface Props {
    onFinish?: Function
};


const { TextArea } = Input;
const { RangePicker } = DatePicker;
const { Dragger } = Upload;

interface AnalysFrom {
    currentFileName: string
    currentYear?: string
}

const SpeciesNameFileModal = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        openModal: openModal
    }));

    const {
        onFinish
    } = props;

    const [form] = Form.useForm<AnalysFrom>();

    const [formData, setFormData] = useState<AnalysFrom>({
        currentFileName: null,
        currentYear: '2023'
    });

    const smartMapRef = useRef(null);
    const delayTimer = useRef(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [currentFileName, setCurrentFileName] = useState("");
    const [analysType, setAnalysType] = useState('');
    const [loading, setLoading] = useState(false);
    const [mergedRowDataList, setMergedRowDataList] = useState<BJHSpeciesInfoType[]>([]);
    const tempSheetData = useRef<TypeWorkBookReadResult[]>(null);
    const tempWorkSheet = useRef<string[][]>(null);
    const [yearOptions, setYearOptions] = useState<SelectOption[]>([]);
    const [currentYear, setCurrentYear] = useState('');

    const [forestArea, setForestArea] = useState('0');
    const [shrubArea, setShrubArea] = useState('0');
    const [grassArea, setGrassArea] = useState('0');
    const [wetlandArea, setWetlandArea] = useState('0');
    const [cultivatedArea, setCultivatedArea] = useState('0');
    const [cityArea, setCityArea] = useState('0');
    const [totalArea, setTotalArea] = useState('0');

    const [forestAreaPercent, setForestAreaPercent] = useState('');
    const [shrubAreaPercent, setShrubAreaPercent] = useState('');
    const [grassAreaPercent, setGrassAreaPercent] = useState('');
    const [wetlandAreaPercent, setWetlandAreaPercent] = useState('');
    const [cultivatedAreaPercent, setCultivatedAreaPercent] = useState('');
    const [cityAreaPercent, setCityAreaPercent] = useState('');

    const [sign, setSign] = useState('1');
    const [WH, setWH] = useState(false);  //水源涵养服务价值
    const [CO, setCO] = useState(false);  //固碳释氧服务价值
    const [CR, setCR] = useState(false);  //气候调节服务价值
    const [AC, setAC] = useState(false);  //空气净化服务价值
    const [WC, setWC] = useState(false);  //水质净化服务价值
    const [SC, setSC] = useState(false);  //固土保肥服务价值
    const [BD, setBD] = useState(false);  //生物多样性服务价值
    const [PN, setPN] = useState(false);  //维持养分循环服务价值
    const [generateTable, setGenerateTable] = useState(false);

    const benefitEvaluation1ParagraphList: WordParagraphBlock[] = [];

    const switchGenerateTable = (e: CheckboxChangeEvent) => {
        setGenerateTable(getCheckBoxChangeEventValue(e))
    };

    type ParagraphType =
        'heading1'
        | 'heading2'
        | 'heading3'
        | 'heading4'
        | 'heading5'
        | 'heading6'
        | 'normalParagraph'
        | 'tableName'
        | 'smallTableName'
        | 'tableAfterDesc'
        | 'failureTitle'
        | 'failureDesc'


    const generateWordParagraBlockByPlainText = (
        plainText: string,
        paragraphType: ParagraphType,
        pageBreakBefore?: boolean,
        pageBreakAfter?: boolean
    ): ReportParagraphBlock => {
        let paragrahBlock: ReportParagraphBlock = {
            blockId: Math.random() + '',
            type: 'Text',
            paragraphInlineStyleRanges: [{
                offset: 0,
                length: plainText.length,
                name: 'inlineStyle_normal',
            }],
            paragraphType: paragraphType,
            text: plainText,
            pageBreakBefore: pageBreakBefore ? pageBreakBefore : false,
            pageBreakAfter: pageBreakAfter ? pageBreakAfter : false,
        }
        return paragrahBlock;
    }

    type InlineTableStyle =
        'normalTable'                     //默认无格式
        | 'speciesBook'             //物种名录表
        | 'protectionSpeciesBook'  //保护物种表
        | 'genusCollectTable'      //属种统计表
        | 'failureTable'

    interface ColSpanInfo {
        rowIndex: number
        colIndex: number
        colSpan: number
    }

    interface RowSpanInfo {
        rowIndex: number
        colIndex: number
        rowSpan: number
    }


    interface TableGenerateResult {
        tableData?: string[][],
        tableHeaderRowNumber?: number
        tableStyle: InlineTableStyle,
        tableColSpanInfoList?: ColSpanInfo[]
        tableRowSpanInfoList?: RowSpanInfo[]
    }

    const generateWordParagraBlockByTableGenerateResult = (
        tableGenerateResult: TableGenerateResult
    ): ReportParagraphBlock => {
        const {
            tableData = [[]],
            tableHeaderRowNumber = 1,
            tableStyle = 'normalTable',
            tableRowSpanInfoList = [],
            tableColSpanInfoList = []
        } = tableGenerateResult;
        let paragrahBlock: ReportParagraphBlock = {
            blockId: getUuid(8),
            type: 'Table',
            paragraphType: 'normalParagraph',
            tableData: tableData,
            tableHeaderRowNumber: tableHeaderRowNumber,
            tableStyle: tableStyle,
            rowSpanInfoList: tableRowSpanInfoList,
            colSpanInfoList: tableColSpanInfoList
        }
        return paragrahBlock;
    }

    const getTableColumnData = (tableData: number[][], columnIndex) => {
        let columnData: number[] = [];
        tableData.forEach(row => {
            columnData.push(row[columnIndex])
        })
        return columnData;
    }

    const getAreaName = (areaType) => {
        switch (areaType) {
            case 'forest':
                return '森林';
                break;
            case 'shrub':
                return '灌丛';
                break;
            case 'grass':
                return '草地';
                break;
            case 'wetland':
                return '湿地和水域';
                break;
            case 'cultivated':
                return '耕地';
                break;
            default:
                break;
        }
    }

    /**
    * 
    * @param total 
    * @param value 
    */
    const caclulateAreaPercent = (total: number, value: number) => {
        return (value / total * 100).toFixed(2);
    }

    useEffect(() => {
        const _forestArea = Number(forestArea);
        const _shrubArea = Number(shrubArea);
        const _grassArea = Number(grassArea);
        const _wetlandArea = Number(wetlandArea);
        const _cultivatedArea = Number(cultivatedArea);
        const _cityArea = Number(cityArea);

        const _totalArea = Number(totalArea);
        let currentUseTotalArea = Number(totalArea);

        //当前最新的数据计算得来的总数
        const _newTotalArea = _forestArea + _shrubArea + _grassArea + _wetlandArea + _cultivatedArea + _cityArea;

        if (_totalArea >= _newTotalArea) {
            //不用处理
        } else {
            currentUseTotalArea = _newTotalArea;
        }
        if (!isEmpty(totalArea) && _totalArea > 0) {
            setForestAreaPercent(caclulateAreaPercent(currentUseTotalArea, _forestArea));
            setShrubAreaPercent(caclulateAreaPercent(currentUseTotalArea, _shrubArea));
            setGrassAreaPercent(caclulateAreaPercent(currentUseTotalArea, _grassArea));
            setWetlandAreaPercent(caclulateAreaPercent(currentUseTotalArea, _wetlandArea));
            setCultivatedAreaPercent(caclulateAreaPercent(currentUseTotalArea, _cultivatedArea));
            setCityAreaPercent(caclulateAreaPercent(currentUseTotalArea, _cityArea));
        }
        setTotalArea(currentUseTotalArea.toString())
    }, [forestArea, shrubArea, grassArea, wetlandArea, cultivatedArea, cityArea])

    const onForestAreaTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        let value = getChangeEventValue(e);
        value = Number(value) + '';
        if (!isNonNegativeNumeric(value)) {
            return toastShort('error', '请输入正确的数字')
        }
        setForestArea(value)
    }

    const onShrubAreaTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        let value = getChangeEventValue(e);
        value = Number(value) + '';
        if (!isNonNegativeNumeric(value)) {
            setTotalArea(totalArea)
            return toastShort('error', '请输入正确的数字')
        }
        setShrubArea(value)
    }

    const onGrassAreaTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        let value = getChangeEventValue(e);
        value = Number(value) + '';
        if (!isNonNegativeNumeric(value)) {
            setTotalArea(totalArea)
            return toastShort('error', '请输入正确的数字')
        }
        setGrassArea(value)
    }

    const onWetlandAreaTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        let value = getChangeEventValue(e);
        value = Number(value) + '';
        if (!isNonNegativeNumeric(value)) {
            setTotalArea(totalArea)
            return toastShort('error', '请输入正确的数字')
        }
        setWetlandArea(value)
    }

    const onCultivatedAreaTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        let value = getChangeEventValue(e);
        value = Number(value) + '';
        if (!isNonNegativeNumeric(value)) {
            setTotalArea(totalArea)
            return toastShort('error', '请输入正确的数字')
        }
        setCultivatedArea(value)
    }

    const onCityAreaTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        let value = getChangeEventValue(e);
        value = Number(value) + '';
        if (!isNonNegativeNumeric(value)) {
            setTotalArea(totalArea)
            return toastShort('error', '请输入正确的数字')
        }
        setCityArea(value)
    }

    const onTotalAreaChange = (e: ChangeEvent<HTMLInputElement>) => {
        let value = getChangeEventValue(e);
        value = Number(value) + '';
        if (!isNonNegativeNumeric(value)) {
            setTotalArea(totalArea)
            return toastShort('error', '请输入正确的数字')
        }
        const _forestArea = Number(forestArea);
        const _shrubArea = Number(shrubArea);
        const _grassArea = Number(grassArea);
        const _wetlandArea = Number(wetlandArea);
        const _cultivatedArea = Number(cultivatedArea);
        const _cityArea = Number(cityArea);
        const realTotalArea = _forestArea + _shrubArea + _grassArea + _wetlandArea + _cultivatedArea + _cityArea;
        let currentUseTotalArea = Number(value);
        // if (currentUseTotalArea < realTotalArea) {
        //     return toastShort('error', '总面积不能小于已填写的各类地类总面积')
        // }
        setForestAreaPercent(caclulateAreaPercent(currentUseTotalArea, _forestArea));
        setShrubAreaPercent(caclulateAreaPercent(currentUseTotalArea, _shrubArea));
        setGrassAreaPercent(caclulateAreaPercent(currentUseTotalArea, _grassArea));
        setWetlandAreaPercent(caclulateAreaPercent(currentUseTotalArea, _wetlandArea));
        setCultivatedAreaPercent(caclulateAreaPercent(currentUseTotalArea, _cultivatedArea));
        setCityAreaPercent(caclulateAreaPercent(currentUseTotalArea, _cityArea));
        setTotalArea(value)
    }


    const onCheckedAllChange = (e: CheckboxChangeEvent) => {
        const isCheckedAll = getCheckBoxChangeEventValue(e);
        setWH(isCheckedAll);
        setCO(isCheckedAll);
        setCR(isCheckedAll);
        setAC(isCheckedAll);
        setWC(isCheckedAll);
        setSC(isCheckedAll);
        setBD(isCheckedAll);
        setPN(isCheckedAll);
    }

    const onSignTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        let _sign = getChangeEventValue(e);
        if (_sign.includes('.')) {
            return toastShort('error', '请勿输入小数点')
        }
        if (Number(_sign) > 6) {
            return toastShort('error', '最多保留到小数点后6位')
        }
        setSign(_sign)
    };

    const onWHChange = (e: CheckboxChangeEvent) => {
        setWH(getCheckBoxChangeEventValue(e))
    }

    const onCOChange = (e: CheckboxChangeEvent) => {
        setCO(getCheckBoxChangeEventValue(e))
    }

    const onCRChange = (e: CheckboxChangeEvent) => {
        setCR(getCheckBoxChangeEventValue(e))
    }

    const onACChange = (e: CheckboxChangeEvent) => {
        setAC(getCheckBoxChangeEventValue(e))
    }

    const onWCChange = (e: CheckboxChangeEvent) => {
        setWC(getCheckBoxChangeEventValue(e))
    }

    const onSCChange = (e: CheckboxChangeEvent) => {
        setSC(getCheckBoxChangeEventValue(e))
    }

    const onBDChange = (e: CheckboxChangeEvent) => {
        setBD(getCheckBoxChangeEventValue(e))
    }

    const onPNChange = (e: CheckboxChangeEvent) => {
        setPN(getCheckBoxChangeEventValue(e))
    }

    const openModal = () => {
        setIsModalOpen(true);
    };

    const handleConfirm = () => {
        const _forestAreaPercent = Number(forestAreaPercent);
        const _shrubAreaPercent = Number(shrubAreaPercent);
        const _grassAreaPercent = Number(grassAreaPercent);
        const _wetlandAreaPercent = Number(wetlandAreaPercent);
        const _cultivatedAreaPercent = Number(cultivatedAreaPercent);
        const realTotalArea = _forestAreaPercent + _shrubAreaPercent + _grassAreaPercent + _wetlandAreaPercent;

        // const _cityAreaPercent = Number(cityAreaPercent);
        const _totalArea = Number(totalArea);
        // if(_totalArea == 0 || realTotalArea == 0){
        //   
        // }
        if (realTotalArea == 0) {
            return toastShort('error', '请至少填入一项地类覆盖状况')
        }
        if (_totalArea == 0) {
            return toastShort('error', '保护地总面积不能为空')
        }
        if (
            WH == false &&
            CO == false &&
            CR == false &&
            AC == false &&
            WC == false &&
            SC == false &&
            BD == false &&
            PN == false
        ) {
            return toastShort('error', '请至少填入一项生态系统服务指标')
        }
        const benefitResultCSV = generateEcologicalBenefit({
            sign: parseInt(sign),
            AT: Number(_totalArea),
            FP: _forestAreaPercent,
            HP: _shrubAreaPercent,
            GP: _grassAreaPercent,
            WP: _wetlandAreaPercent,
            CP: _cultivatedAreaPercent,
            WH,
            CO,
            CR,
            AC,
            WC,
            SC,
            BD,
            PN
        })
        console.log("benefitResultCSV--->", benefitResultCSV)
        let areaTypeList = [];
        let targetTypeList = [];
        if (_forestAreaPercent != 0) {
            areaTypeList.push('forest')
        }
        if (_shrubAreaPercent != 0) {
            areaTypeList.push('shrub')
        }
        if (_grassAreaPercent != 0) {
            areaTypeList.push('grass')
        }
        if (_wetlandAreaPercent != 0) {
            areaTypeList.push('wetland')
        }
        if (_cultivatedAreaPercent != 0) {
            areaTypeList.push('cultivated')
        }
        if (WH) {
            targetTypeList.push('WH')
        }
        if (CO) {
            targetTypeList.push('CO')
        }
        if (CR) {
            targetTypeList.push('CR')
        }
        if (AC) {
            targetTypeList.push('AC')
        }
        if (WC) {
            targetTypeList.push('WC')
        }
        if (SC) {
            targetTypeList.push('SC')
        }
        if (BD) {
            targetTypeList.push('BD')
        }
        if (PN) {
            targetTypeList.push('PN')
        }
        console.log("targetTypeList--->", targetTypeList);
        const protectlandName = '保护地';
        let totalParagraphDescText = '';
        let WHParagraphDescText = ''; //水源涵养服务价值描述文本
        let COParagraphDescText = ''; //固碳释氧服务价值描述文本
        let CRParagraphDescText = ''; //气候调节服务价值描述文本
        let ACParagraphDescText = ''; //空气净化服务价值描述文本
        let WCParagraphDescText = ''; //水质净化服务价值描述文本
        let SCParagraphDescText = ''; //固土保肥服务价值描述文本
        let BDParagraphDescText = ''; //生物多样性服务价值描述文本
        let PNParagraphDescText = ''; //维持养分循环价值描述文本
        const tableHeader1: string[] = ["生态系统服务"];
        const tableHeader2: string[] = ["总价值", "单位面积总价值"];
        //开始生成生态系统服务总价值描述
        for (let i = 0; i < benefitResultCSV[0].length; i++) {
            const currentColumnData = getTableColumnData(benefitResultCSV, i);
            const currentTargetTotalData = benefitResultCSV[0][i];
            const currentTargetUnitData = benefitResultCSV[1][i];
            if (i == benefitResultCSV[0].length - 1) {
                tableHeader1.push("保护地整体");
                console.log("计算总计------->", currentColumnData)
                let totalText = `通过测算，规划后${protectlandName}的生态服务功能总价值约为${currentColumnData[0]}万元，单位面积生态服务功能价值为${currentColumnData[1]}万元/(h㎡·a)。其中`;
                totalParagraphDescText = totalText + totalParagraphDescText;
                targetTypeList.forEach((targetType, targetTypeIndex) => {

                    switch (targetType) {
                        case 'WH':
                            if (!tableHeader2.includes('水源涵养价值')) {
                                tableHeader2.push("水源涵养价值")
                            }
                            if (!tableHeader2.includes('水源涵养单位面积价值')) {
                                tableHeader2.push("水源涵养单位面积价值")
                            }
                            WHParagraphDescText = `水源涵养指生态系统对降水的截留、吸收和贮存以及将地表水转为地表径流或地下水的作用。保护地的自然生态系统不仅具有较好的吸收降水功能，而且水分在土壤内的渗透，能对水体中的各种污染进行直接过滤和净化。可见，保护好保护区内的各种生态系统，可以增加有效水，减少无效水，起到蓄水和调节水量的作用，对涵养水源具有重要意义。通过测算，规划后${protectlandName}的水源涵养服务总价值约为${currentTargetTotalData}万元，单位面积水源涵养价值为${currentTargetUnitData}万元/(h㎡·a)。其中` + WHParagraphDescText;
                            break;
                        case 'CO':
                            if (!tableHeader2.includes('固碳释氧价值')) {
                                tableHeader2.push("固碳释氧价值")
                            }
                            if (!tableHeader2.includes('固碳释氧单位面积价值')) {
                                tableHeader2.push("固碳释氧单位面积价值")
                            }
                            COParagraphDescText = `固碳释氧指生态系统中的各种植被通过光合作用吸收二氧化碳，释放氧气，有效地维持大气中氧气和二氧化碳的比例平衡的功能。自然保护地中的植被可以看做是天然的“氧气制造工厂”和“二氧化碳净化工厂”，氧气是地球上绝大多数生物生存的基本物质条件，吸收二氧化碳能够有效降低大气中的温室气体，缓解全球变暖。通过测算，规划后${protectlandName}的固碳释氧服务总价值约为${currentTargetTotalData}万元，单位面积固碳释氧价值为${currentTargetUnitData}万元/(h㎡·a)。其中` + COParagraphDescText
                            break;
                        case 'CR':
                            if (!tableHeader2.includes('气候调节价值')) {
                                tableHeader2.push("气候调节价值")
                            }
                            if (!tableHeader2.includes('气候调节单位面积价值')) {
                                tableHeader2.push("气候调节单位面积价值")
                            }
                            CRParagraphDescText = `气候调节指生态系统调节区域气温、降水和风力等气象要素的能力，生态系统能够有效地维持区域气候的稳定，降低极端气象事件发生的概率，提高人与其他生物的环境舒适度。通过测算，规划后${protectlandName}的气候调节服务总价值约为${currentTargetTotalData}万元，单位面积气候调节价值为${currentTargetUnitData}万元/(h㎡·a)。其中` + CRParagraphDescText;
                            break;
                        case 'AC':
                            if (!tableHeader2.includes('空气净化价值')) {
                                tableHeader2.push("空气净化价值")
                            }
                            if (!tableHeader2.includes('空气净化单位面积价值')) {
                                tableHeader2.push("空气净化单位面积价值")
                            }
                            ACParagraphDescText = `空气净化指生态系统对二氧化硫、氟化物、氮氧化物、粉尘、重金属等大气污染物有吸收、过滤、阻隔和分解，以及降低噪音、提供负离子等功能。保护地分布有大面积的植被，其净化空气作用显著。此外，某些树叶的挥发性气体及根系的分泌物可以杀灭空气中的一些病源菌，对大气进行消毒，成为“天然的防疫员”。在大气污染和其它各种污染日益严重的现代社会里，生态系统改善大气质量的作用日益受到重视。通过测算，规划后${protectlandName}的空气净化服务总价值约为${currentTargetTotalData}万元，单位面积空气净化价值为${currentTargetUnitData}万元/(h㎡·a)。其中` + ACParagraphDescText;
                            break;
                        case 'WC':
                            if (!tableHeader2.includes('水质净化价值')) {
                                tableHeader2.push("水质净化价值")
                            }
                            if (!tableHeader2.includes('水质净化单位面积价值')) {
                                tableHeader2.push("水质净化单位面积价值")
                            }
                            WCParagraphDescText = `水质净化指生态系统通过生物化学反应对氮氧化物、硫氧化物、磷、COD、BOD等水体污染物吸收、过滤、阻隔和分解的作用。保护地中土壤、植被和微生物等的净化水体作用显著，在不超出生态系统承载力的情况下，生态系统能够有效地净化水体中的污染物，达到生物可利用的标准。通过测算，规划后${protectlandName}的水质净化服务总价值约为${currentTargetTotalData}万元，单位面积水质净化价值为${currentTargetUnitData}万元/(h㎡·a)。其中` + WCParagraphDescText
                            break;
                        case 'SC':
                            if (!tableHeader2.includes('固土保肥价值')) {
                                tableHeader2.push("固土保肥价值")
                            }
                            if (!tableHeader2.includes('固土保肥单位面积价值')) {
                                tableHeader2.push("固土保肥单位面积价值")
                            }
                            SCParagraphDescText = `土壤侵蚀是巨大的环境问题。它能使土壤肥力降低，土层变浅。山区土层浅薄，在强烈的雨水侵蚀下，可以在很短的时间内成为裸露的岩石地。如果覆盖有森林植被，就会减少土壤侵蚀和水土流失。保护地内森林面积大、覆盖率高、植被保存完好、林下枯枝落叶层厚、土壤渗透性强，对防止地表径流效果显著。通过测算，规划后${protectlandName}的固土保肥服务总价值约为${currentTargetTotalData}万元，单位面积固土保肥价值为${currentTargetUnitData}万元/(h㎡·a)。其中` + SCParagraphDescText;
                            break;
                        case 'BD':
                            if (!tableHeader2.includes('生物多样性价值')) {
                                tableHeader2.push("生物多样性价值")
                            }
                            if (!tableHeader2.includes('生物多样性单位面积价值')) {
                                tableHeader2.push("生物多样性单位面积价值")
                            }
                            BDParagraphDescText = `保护地内的野生动植物物种极为丰富，生态系统多样，是珍稀濒危物种重要栖息地和极为宝贵的“基因资源库”。近年来，我国生物多样性保护已从单一物种的保护转移到物种生境及生态系统的保护。保护生境是保护生物多样性最有效的方法。自然保护地是生物多样性就地保护的最佳场所，它的建立和有效管理是生物多样性保护的战略举措。通过测算，规划后${protectlandName}的生物多样性服务总价值约为${currentTargetTotalData}万元，单位面积生物多样性价值为${currentTargetUnitData}万元/(h㎡·a)。其中` + BDParagraphDescText;
                            break;
                        case 'PN':
                            if (!tableHeader2.includes('维持养分循环价值')) {
                                tableHeader2.push("维持养分循环价值")
                            }
                            if (!tableHeader2.includes('维持养分循环单位面积价值')) {
                                tableHeader2.push("维持养分循环单位面积价值")
                            }
                            PNParagraphDescText = `生态系统中植被的生长能够积累营养物质。植被在其生长过程中不断地从周围环境中吸收N、P、K等营养物质，并贮存在各器官中。植被积累营养物质的功能能够供给其他生物生存与繁殖，同时降低下游面源污染及水体富营养化，维持营养物质循环的平衡。通过测算，规划后${protectlandName}的维持养分循环服务总价值约为${currentTargetTotalData}万元，单位面积维持养分循环价值为${currentTargetUnitData}万元/(h㎡·a)。其中` + PNParagraphDescText;
                            break;
                    }
                })
            } else {
                const currentAreaType = areaTypeList[i];
                const currentAreaName = getAreaName(currentAreaType);
                tableHeader1.push(currentAreaName)
                totalParagraphDescText += `${currentAreaName}提供的生态服务功能总价值约为${currentTargetTotalData}万元，相应的单位面积生态服务功能价值为${currentTargetUnitData}万元/(h㎡·a)；`
                const lastAreaType = areaTypeList[areaTypeList.length - 1];

                targetTypeList.forEach((targetType, targetTypeIndex) => {

                    const currentTargetTotalData = currentColumnData[targetTypeIndex + 2];
                    const currentTargetUnitData = currentColumnData[targetTypeIndex + 3];
                    switch (targetType) {
                        case 'WH':
                            WHParagraphDescText += `${currentAreaName}提供的水源涵养总价值约为${currentTargetTotalData}万元，相应的单位面积水源涵养价值为${currentTargetUnitData}万元/(h㎡·a)；`
                            break;
                        case 'CO':
                            COParagraphDescText += `${currentAreaName}提供的固碳释氧总价值约为${currentTargetTotalData}万元，相应的单位面积固碳释氧价值为${currentTargetUnitData}万元/(h㎡·a)；`
                            break;
                        case 'CR':
                            CRParagraphDescText += `${currentAreaName}提供的气候调节总价值约为${currentTargetTotalData}万元，相应的单位面积气候调节价值为${currentTargetUnitData}万元/(h㎡·a)；`
                            break;
                        case 'AC':
                            ACParagraphDescText += `${currentAreaName}提供的空气净化总价值约为${currentTargetTotalData}万元，相应的单位面积空气净化价值为${currentTargetUnitData}万元/(h㎡·a)；`
                            break;
                        case 'WC':
                            WCParagraphDescText += `${currentAreaName}提供的水质净化总价值约为${currentTargetTotalData}万元，相应的单位面积水质净化价值为${currentTargetUnitData}万元/(h㎡·a)；`
                            break;
                        case 'SC':
                            SCParagraphDescText += `${currentAreaName}提供的固土保肥总价值约为${currentTargetTotalData}万元，相应的单位面积固土保肥价值为${currentTargetUnitData}万元/(h㎡·a)；`
                            break;
                        case 'BD':
                            BDParagraphDescText += `${currentAreaName}提供的生物多样性总价值约为${currentTargetTotalData}万元，相应的单位面积生物多样性价值为${currentTargetUnitData}万元/(h㎡·a)；`
                            break;
                        case 'PN':
                            PNParagraphDescText += `${currentAreaName}提供的维持养分循环总价值约为${currentTargetTotalData}万元，相应的单位面积维持养分循环价值为${currentTargetUnitData}万元/(h㎡·a)；`
                            break;
                    }

                })
            }
        }
        console.log("tableHeader1--->", tableHeader1)
        console.log("tableHeader2--->", tableHeader2)
        let tableData: string[][] = [tableHeader1];
        // tableHeader1.forEach((headerName1, headerName1Index) => {
        //     let rowData: string[] = [];
        //     if (headerName1Index > 0) {
        //         rowData.push(tableHeader2[headerName1Index])
        //         tableHeader2.forEach((headerName2, headerName2Index) => {
        //             console.log("测试下标", headerName2Index, headerName1Index)
        //             rowData.push(benefitResultCSV[headerName2Index][headerName1Index - 1] + '')
        //         })
        //         tableData.push(rowData)
        //     }
        // })
        tableHeader2.forEach((headerName2, headerName2Index) => {
            let rowData = [headerName2];
            tableHeader1.forEach((headerName1, headerName1Index) => {
                if (headerName1Index > 0) {
                    console.log("测试", benefitResultCSV[headerName2Index][headerName1Index - 1])
                    if (headerName1Index > 0) {
                        rowData.push(benefitResultCSV[headerName2Index][headerName1Index - 1] + '')
                    }

                }
            })
            tableData.push(rowData)
        })
        console.log("ssssss", tableData)
        console.log("totalParagraphDescText--->", totalParagraphDescText);
        console.log("WHParagraphDescText--->", WHParagraphDescText);
        console.log("COParagraphDescText--->", COParagraphDescText);
        console.log("CRParagraphDescText--->", CRParagraphDescText);
        console.log("ACParagraphDescText--->", ACParagraphDescText);
        console.log("WCParagraphDescText--->", WCParagraphDescText);
        console.log("SCParagraphDescText--->", SCParagraphDescText);
        console.log("BDParagraphDescText--->", BDParagraphDescText);
        console.log("PNParagraphDescText--->", PNParagraphDescText);
        let wordParagraphList: ReportParagraphBlock[] = [];
        wordParagraphList.push(generateWordParagraBlockByPlainText("生态效益分析", 'heading1'))
        if (!isEmpty(totalParagraphDescText)) {
            wordParagraphList.push(generateWordParagraBlockByPlainText(totalParagraphDescText, 'normalParagraph'))
        }
        if (!isEmpty(WHParagraphDescText)) {
            wordParagraphList.push(generateWordParagraBlockByPlainText(WHParagraphDescText, 'normalParagraph'))
        }
        if (!isEmpty(COParagraphDescText)) {
            wordParagraphList.push(generateWordParagraBlockByPlainText(COParagraphDescText, 'normalParagraph'))
        }
        if (!isEmpty(CRParagraphDescText)) {
            wordParagraphList.push(generateWordParagraBlockByPlainText(CRParagraphDescText, 'normalParagraph'))
        }
        if (!isEmpty(ACParagraphDescText)) {
            wordParagraphList.push(generateWordParagraBlockByPlainText(ACParagraphDescText, 'normalParagraph'))
        }
        if (!isEmpty(WCParagraphDescText)) {
            wordParagraphList.push(generateWordParagraBlockByPlainText(WCParagraphDescText, 'normalParagraph'))
        }
        if (!isEmpty(SCParagraphDescText)) {
            wordParagraphList.push(generateWordParagraBlockByPlainText(SCParagraphDescText, 'normalParagraph'))
        }
        if (!isEmpty(BDParagraphDescText)) {
            wordParagraphList.push(generateWordParagraBlockByPlainText(BDParagraphDescText, 'normalParagraph'))
        }
        if (!isEmpty(PNParagraphDescText)) {
            wordParagraphList.push(generateWordParagraBlockByPlainText(PNParagraphDescText, 'normalParagraph'))
        }
        if (generateTable) {
            wordParagraphList.push(generateWordParagraBlockByPlainText(`${protectlandName}生态效益`, 'smallTableName'))
            wordParagraphList.push(generateWordParagraBlockByTableGenerateResult({
                tableStyle: 'normalTable',
                tableData: tableData
            }))
        }
        console.log("wordParagraphList--->", wordParagraphList);
        setSubmitLoading(true);
        let statisticalAnalysisParams = {
            data: JSON.stringify({
                paragraphList: wordParagraphList
            })
        }
        systemApi.exportWordReport(statisticalAnalysisParams)
            .then(res => {
                downloadAndRenameFile(res.data.url, '生态效益分析');
                setSubmitLoading(false);
            })
            .catch(err => {
                console.log("失败", err)
            })
    }

    const handleCancel = () => {
        setIsModalOpen(false);
    }


    return (
        <Modal
            title={"生态效益分析"}
            open={isModalOpen}
            onOk={handleConfirm}
            onCancel={handleCancel}
            okText={'确 认'}
            cancelText={'取 消'}
            width={'800px'}
            maskClosable={false}
            confirmLoading={submitLoading}
            centered
        >
            <div className='word-editor-plugins-content benefit-evaluation-content'>
                <div className='edit-benefit-header'>
                    <div className='edit-benefit-title'>
                        保护地地表覆盖:面积（公顷）
                        <Tooltip title={'请至少填写一项地类覆盖情况，系统会根据填写的地表覆盖状况信息自动计算比例，并输出对应的报告文本。'}>
                            <QuestionCircleOutlined style={{ cursor: 'pointer' }} />
                        </Tooltip>
                    </div>
                    <div className='edit-benefit-title'>比例（%）</div>
                </div>
                <div className='edit-benefit-header'>
                    <Input
                        placeholder='请输入'
                        value={forestArea}
                        style={{ width: 110, textAlign: 'center' }}
                        type={'number'}
                        onChange={onForestAreaTextChange}
                    ></Input>
                    <div className='edit-benefit-header-center'>
                        <div className='edit-benefit-header-font'>
                            <img className='edit-benefit-header-font-img' src={Image1} />
                        </div>
                        <div className='edit-benefit-header-text'>森林</div>
                    </div>
                    <Input
                        placeholder='自动计算'
                        value={forestAreaPercent}
                        style={{ width: 110, textAlign: 'center' }}
                        disabled
                    ></Input>
                </div>
                <div className='edit-benefit-header'>
                    <Input
                        placeholder='请输入'
                        value={shrubArea}
                        onChange={onShrubAreaTextChange}
                        type={'number'}
                        style={{ width: 110, textAlign: 'center' }}
                    ></Input>
                    <div className='edit-benefit-header-center'>
                        <div className='edit-benefit-header-font'>
                            <img className='edit-benefit-header-font-img' src={Image2} />
                        </div>
                        <div className='edit-benefit-header-text'>灌丛</div>
                    </div>
                    <Input
                        placeholder='自动计算'
                        value={shrubAreaPercent}
                        style={{ width: 110, textAlign: 'center' }}
                        disabled
                    ></Input>
                </div>
                <div className='edit-benefit-header'>
                    <Input
                        placeholder='请输入'
                        value={grassArea}
                        onChange={onGrassAreaTextChange}
                        type={'number'}
                        style={{ width: 110, textAlign: 'center' }}
                    ></Input>
                    <div className='edit-benefit-header-center'>
                        <div className='edit-benefit-header-font'>
                            <img className='edit-benefit-header-font-img' src={Image3} />
                        </div>
                        <div className='edit-benefit-header-text'>草地</div>
                    </div>
                    <Input
                        placeholder='自动计算'
                        value={grassAreaPercent}
                        style={{ width: 110, textAlign: 'center' }}
                        disabled
                    ></Input>
                </div>
                <div className='edit-benefit-header'>
                    <Input
                        placeholder='请输入'
                        value={wetlandArea}
                        onChange={onWetlandAreaTextChange}
                        type={'number'}
                        style={{ width: 110, textAlign: 'center' }}
                    ></Input>
                    <div className='edit-benefit-header-center'>
                        <div className='edit-benefit-header-font'>
                            <img className='edit-benefit-header-font-img' src={Image4} />
                        </div>
                        <div className='edit-benefit-header-text'>水域和湿地</div>
                    </div>
                    <Input
                        placeholder='自动计算'
                        value={wetlandAreaPercent}
                        style={{ width: 110, textAlign: 'center' }}
                        disabled
                    ></Input>
                </div>
                <div className='edit-benefit-header'>
                    <Input
                        placeholder='请输入'
                        value={cultivatedArea}
                        type={'number'}
                        onChange={onCultivatedAreaTextChange}
                        style={{ width: 110, textAlign: 'center' }}
                    ></Input>
                    <div className='edit-benefit-header-center'>
                        <div className='edit-benefit-header-font'>
                            <img className='edit-benefit-header-font-img' src={Image5} />
                        </div>
                        <div className='edit-benefit-header-text'>耕地</div>
                    </div>
                    <Input
                        placeholder='自动计算'
                        value={cultivatedAreaPercent}
                        style={{ width: 110, textAlign: 'center' }}
                        disabled
                    ></Input>
                </div>
                <div className='edit-benefit-header'>
                    <Input
                        placeholder='请输入'
                        style={{ width: 110, textAlign: 'center' }}
                        value={cityArea}
                        type={'number'}
                        onChange={onCityAreaTextChange}
                    ></Input>
                    <div className='edit-benefit-header-center'>
                        <div className='edit-benefit-header-font'>
                            <img className='edit-benefit-header-font-img' src={Image6} />
                        </div>
                        <div className='edit-benefit-header-text'>城市</div>
                    </div>
                    <Input
                        placeholder='自动计算'
                        value={cityAreaPercent}
                        style={{ width: 110, textAlign: 'center' }}
                        disabled
                    ></Input>
                </div>
                <div className='edit-benefit-header'>
                    <Input
                        placeholder='请输入'
                        style={{ width: 110, textAlign: 'center' }}
                        value={totalArea}
                        type={'number'}
                        onChange={onTotalAreaChange}
                    ></Input>
                    <div className='edit-benefit-header-center'>
                        {/* <div className='edit-benefit-header-font'>
                        <img className='edit-benefit-header-font-img' src={Image6} />
                    </div> */}
                        <div className='edit-benefit-header-text' style={{ whiteSpace: 'pre-wrap' }}>{'保护地\n总面积'}</div>
                    </div>
                    <Input
                        placeholder='自动计算'
                        style={{ width: 110, textAlign: 'center' }}
                        value={'100'}
                        disabled
                    ></Input>
                </div>
                {/* <div className='edit-benefit-header'>
                <div style={{ fontSize: 14 }} className='edit-benefit-header-text'>保护地总面积(公顷)</div>
                <Input placeholder='0~100' style={{ width: 110, textAlign: 'center' }}></Input>
            </div> */}
                <div className='edit-benefit-line'></div>
                <div className='edit-benefit-header'>
                    <div className='edit-benefit-title'>生态系统服务指标</div>
                    <Checkbox onChange={onCheckedAllChange}>全选</Checkbox>
                </div>
                <div className='edit-benefit-bnt-more'>
                    <div
                        className='edit-benefit-bnt-item'
                    // onClick={switchWHChecked}
                    >
                        <Checkbox
                            className='edit-benefit-bnt-checkbox'
                            checked={AC}
                            onChange={onACChange}
                        >
                            空气净化
                        </Checkbox>

                    </div>
                    <div
                        className='edit-benefit-bnt-item'
                    // onClick={switchCOChecked}
                    >
                        <Checkbox
                            className='edit-benefit-bnt-checkbox'
                            checked={WH}
                            onChange={onWHChange}
                        >
                            水源涵养
                        </Checkbox>
                    </div>
                    <div
                        className='edit-benefit-bnt-item'
                    // onClick={switchCRChecked}
                    >
                        <Checkbox
                            key={'CO'}
                            className='edit-benefit-bnt-checkbox'
                            checked={CO}
                            onChange={onCOChange}
                        >
                            固碳释氧
                        </Checkbox>

                    </div>
                    <div
                        className='edit-benefit-bnt-item'
                    // onClick={switchACChecked}
                    >
                        <Checkbox
                            key={'CR'}
                            className='edit-benefit-bnt-checkbox'
                            checked={CR}
                            onChange={onCRChange}
                        >
                            气候调节
                        </Checkbox>
                    </div>
                    <div
                        className='edit-benefit-bnt-item'
                    // onClick={switchWCChecked}
                    >
                        <Checkbox
                            className='edit-benefit-bnt-checkbox'
                            checked={WC}
                            onChange={onWCChange}
                        >
                            水质净化
                        </Checkbox>
                    </div>
                    <div
                        className='edit-benefit-bnt-item'
                    // onClick={switchSCChecked}
                    >
                        <Checkbox
                            className='edit-benefit-bnt-checkbox'
                            checked={SC}
                            onChange={onSCChange}
                        >
                            固土保肥
                        </Checkbox>
                    </div>
                    <div
                        className='edit-benefit-bnt-item'
                    // onClick={switchBDChecked}
                    >
                        <Checkbox
                            className='edit-benefit-bnt-checkbox'
                            checked={PN}
                            onChange={onPNChange}
                        >
                            维持养分营养
                        </Checkbox>
                    </div>
                    <div
                        className='edit-benefit-bnt-item'
                    // onClick={switchPNChecked}
                    >
                        <Checkbox
                            className='edit-benefit-bnt-checkbox'
                            checked={BD}
                            onChange={onBDChange}
                        >
                            生物多样性保护
                        </Checkbox>
                    </div>
                </div>
                <div className='edit-benefit-header'>
                    <div>
                        小数点后保留位数
                        <Input
                            placeholder='1'
                            value={sign}
                            onChange={onSignTextChange}
                            style={{ width: 32, textAlign: 'center', height: 24, margin: '0 6px' }}
                        ></Input>
                        位
                    </div>
                    <Checkbox
                        checked={generateTable}
                        onChange={switchGenerateTable}
                    >生成表格</Checkbox>
                </div>
                {/* <Button
                type={'primary'}
                style={{ width: '100%', marginTop: 12 }}
                onClick={handleGenerateEcologicalBenefit}
                size={'middle'}
            >生成</Button> */}
            </div>
        </Modal>
    )

}

export default forwardRef(SpeciesNameFileModal)